package com.bedpotato.service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.bedpotato.constants.ProxyClawerConstants;
import com.bedpotato.http.BasicHttpMethod;
import com.bedpotato.mapper.ProxyMapper;
import com.bedpotato.po.ProxyPO;
import com.bedpotato.thread.ProxyTestThread;

@Service
public class ProxyTestService {
	@Resource
	ProxyMapper proxyMapper;
	Logger logger = Logger.getLogger(ProxyTestService.class);
	/**
	 * 通过发送GET请求判断代理是否可用
	 * 
	 * @author LiALuN
	 * @param proxyPO
	 * @return
	 */
	public boolean isProxyAvailable(ProxyPO proxyPO) {
		BasicHttpMethod basicHttpMethod = new BasicHttpMethod();
		try {
			String str = basicHttpMethod.getByAnonymousProxy(
					ProxyClawerConstants.TESTURL, proxyPO);
			if (str.contains("新浪微博")) {
				proxyPO.setPingcount(proxyPO.getPingcount() + 1);
				proxyPO.setSuccesscount(proxyPO.getSuccesscount() + 1);
				proxyMapper.updateProxy(proxyPO);
				return true;
			}
		} catch (Exception e) {
			// 代理不可用的情况
		}
		proxyPO.setPingcount(proxyPO.getPingcount() + 1);
		proxyMapper.updateProxy(proxyPO);
		return false;
	}

	/**
	 * 测试数据库中所有的代理
	 * 
	 * @author LiALuN
	 */
	public void testAllProxy() {
		List<ProxyPO> proxyList = proxyMapper.getAllProxy();
		ExecutorService executorService = Executors
				.newFixedThreadPool(ProxyClawerConstants.PROXY_TEST_THREAD_NUMBER);
		logger.info("开始进行全部代理测试,测试" + proxyList.size() + "个代理");
		for (ProxyPO proxyPO : proxyList) {
			ProxyTestThread proxyTestThread = ProxyClawerConstants.applicationContext.getBean("proxyTestThread",ProxyTestThread.class);
			proxyTestThread.setProxyPO(proxyPO);
			executorService.execute(proxyTestThread);
		}
	}
}
